class MDViewer {
    constructor() {
        this.drawer = new mdui.Drawer('#main-drawer', { swipe: true });
        this.expandedFolders = new Set();
        this.initEvents();
        this.loadStructure();
        this.initRouter();
        this.restorePersistedState();
    }

    // 初始化事件监听
    initEvents() {
        document.getElementById('fileTree').addEventListener('click', (e) => {
            const folderItem = e.target.closest('.folder-item');
            const fileItem = e.target.closest('.file-item');
            
            if (folderItem) {
                e.stopPropagation();
                this.toggleFolder(folderItem);
            }
            if (fileItem) this.loadDocument(fileItem.dataset.ulid);
        });

        window.addEventListener('resize', () => {
            if (window.innerWidth >= 768 && this.drawer.isOpen()) {
                this.drawer.close();
            }
        });
    }

    // 加载文档结构
    async loadStructure() {
        try {
            const res = await fetch('/api/structure');
            const structure = await res.json();
            this.renderTree(structure);
            this.restoreExpandedFolders();
            mdui.mutation();
        } catch (err) {
            this.showError('文档结构加载失败');
        }
    }

    // 渲染目录树
    renderTree(nodes, parentElem = document.getElementById('fileTree')) {
        parentElem.innerHTML = nodes.map(node => {
            const isExpanded = this.expandedFolders.has(node.id);
            
            return node.type === 'dir' 
                ? this.createFolderItem(node, isExpanded)
                : this.createFileItem(node);
        }).join('');
    }

    // 创建文件夹项
    createFolderItem(node, isExpanded) {
        return `
            <div class="mdui-list-item mdui-ripple folder-item ${isExpanded ? 'expanded' : ''}" 
                 data-ulid="${node.id}">
                <i class="mdui-icon material-icons folder-icon">
                    ${isExpanded ? 'expand_more' : 'chevron_right'}
                </i>
                <div class="mdui-list-item-content">${node.name}</div>
                ${node.children?.length ? `<span class="mdui-badge">${node.children.length}</span>` : ''}
            </div>
            <div class="sublist mdui-list" 
                 data-parent="${node.id}" 
                 style="display: ${isExpanded ? 'block' : 'none'}">
                ${node.children?.map(child => this.createTreeNode(child)).join('')}
            </div>
        `;
    }

    // 创建文件项
    createFileItem(node) {
        return `
            <div class="mdui-list-item mdui-ripple file-item" data-ulid="${node.id}">
                <i class="mdui-icon material-icons">insert_drive_file</i>
                <div class="mdui-list-item-content">${node.name}</div>
            </div>
        `;
    }

    // 创建树节点
    createTreeNode(node) {
        return node.type === 'dir' 
            ? this.createFolderItem(node, false) 
            : this.createFileItem(node);
    }

    // 切换文件夹状态
    async toggleFolder(item) {
        const ulid = item.dataset.ulid;
        const sublist = item.nextElementSibling;
        
        if (this.expandedFolders.has(ulid)) {
            await this.collapseFolder(item, sublist);
            this.expandedFolders.delete(ulid);
        } else {
            await this.expandFolder(item, sublist);
            this.expandedFolders.add(ulid);
        }
        
        this.persistState();
    }

    // 展开文件夹
    async expandFolder(item, sublist) {
        if (!sublist.children.length) {
            await this.loadSubItems(item.dataset.ulid, sublist);
        }

        item.classList.add('expanding');
        sublist.style.display = 'block';
        const height = sublist.scrollHeight;
        
        return new Promise(resolve => {
            sublist.style.height = '0';
            sublist.style.overflow = 'hidden';
            
            requestAnimationFrame(() => {
                sublist.style.transition = 'height 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
                sublist.style.height = `${height}px`;
                
                setTimeout(() => {
                    sublist.style.height = '';
                    sublist.style.overflow = '';
                    item.classList.replace('expanding', 'expanded');
                    item.querySelector('.folder-icon').textContent = 'expand_more';
                    resolve();
                }, 300);
            });
        });
    }

    // 折叠文件夹
    async collapseFolder(item, sublist) {
        item.classList.add('collapsing');
        const height = sublist.scrollHeight;
        
        return new Promise(resolve => {
            sublist.style.height = `${height}px`;
            sublist.style.overflow = 'hidden';
            
            requestAnimationFrame(() => {
                sublist.style.transition = 'height 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
                sublist.style.height = '0';
                
                setTimeout(() => {
                    sublist.style.display = 'none';
                    sublist.style.height = '';
                    item.classList.remove('collapsing', 'expanded');
                    item.querySelector('.folder-icon').textContent = 'chevron_right';
                    resolve();
                }, 300);
            });
        });
    }

    // 加载子项内容
    async loadSubItems(ulid, sublist) {
        try {
            sublist.innerHTML = '<div class="mdui-spinner"></div>';
            
            const res = await fetch(`/api/structure?parent=${ulid}`);
            const children = await res.json();
            
            sublist.innerHTML = children.map(child => 
                this.createTreeNode(child)
            ).join('');
            
            mdui.mutation();
        } catch (err) {
            this.showError('子项加载失败');
            sublist.innerHTML = '';
        }
    }

    // 加载文档内容（含复制功能）
    async loadDocument(ulid) {
        try {
            // 更新URL参数
            const newUrl = new URL(window.location);
                newUrl.searchParams.set('id', ulid);
                window.history.pushState(
                    { ulid }, 
                    '',
                    newUrl.toString()
                );

            if (window.innerWidth < 768) {
                this.drawer.close();
            }

            const contentArea = document.getElementById('content');
            contentArea.innerHTML = '<div class="mdui-spinner"></div>';

            const res = await fetch(`/api/doc/${ulid}`);
            if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
            
            const { content, meta } = await res.json();
            
            contentArea.innerHTML = marked.parse(content, {
                highlight: (code, lang) => hljs.highlightAuto(code).value
            });

            this.addCopyButtons();

            document.title = `${meta.name} - ByUsi帮助中心`;
            hljs.highlightAll();
            mdui.mutation();
        } catch (err) {
            this.showError(`文档加载失败: ${err.message}`);
        }
    }

    // 代码复制功能实现
    addCopyButtons() {
        document.querySelectorAll('pre code').forEach(codeBlock => {
            const pre = codeBlock.parentElement;
            if (pre.classList.contains('has-copy-btn')) return;

            const container = document.createElement('div');
            container.className = 'copy-container';

            const copyBtn = document.createElement('button');
            copyBtn.className = 'mdui-btn mdui-btn-icon mdui-ripple copy-btn';
            copyBtn.innerHTML = '<i class="mdui-icon material-icons">content_copy</i>';

            const successMsg = document.createElement('div');
            successMsg.className = 'copy-success';
            successMsg.textContent = '✓ 已复制';

            copyBtn.addEventListener('click', async () => {
                try {
                    await navigator.clipboard.writeText(codeBlock.textContent);
                    successMsg.style.display = 'block';
                    setTimeout(() => successMsg.style.display = 'none', 2000);
                } catch (err) {
                    this.showError('复制失败，请手动选择文本');
                }
            });

            container.appendChild(copyBtn);
            container.appendChild(successMsg);
            pre.prepend(container);
            pre.classList.add('has-copy-btn');
        });
    }

    // 初始化路由
    initRouter() {
        window.addEventListener('popstate', (e) => {
            this.handleUrlUpdate();
        });

        this.handleUrlUpdate();
    }

    // 处理URL更新
    handleUrlUpdate() {
        const urlParams = new URLSearchParams(location.search);
        const docId = urlParams.get('id');
        
        if (docId) {
            this.loadDocument(docId);
        } else if (location.pathname === '/' && !location.search) {
            document.getElementById('content').innerHTML = `
                <div id="welcome-message" class="mdui-text-center mdui-text-color-theme-text">
                    <h3>欢迎访问ByUsi帮助中心</h3>
                    <p>请从左侧目录选择文档，或直接输入带?id参数的URL访问</p>
                </div>
            `;
            document.title = 'ByUsi帮助中心';
        }
    }

    // 持久化状态
    persistState() {
        localStorage.setItem('expandedFolders', JSON.stringify([...this.expandedFolders]));
    }

    // 恢复持久化状态
    restorePersistedState() {
        const savedState = localStorage.getItem('expandedFolders');
        if (savedState) {
            this.expandedFolders = new Set(JSON.parse(savedState));
        }
    }

    // 恢复展开状态
    restoreExpandedFolders() {
        this.expandedFolders.forEach(ulid => {
            const item = document.querySelector(`.folder-item[data-ulid="${ulid}"]`);
            if (item) {
                const sublist = item.nextElementSibling;
                item.classList.add('expanded');
                item.querySelector('.folder-icon').textContent = 'expand_more';
                sublist.style.display = 'block';
            }
        });
    }

    // 显示错误提示
    showError(message) {
        mdui.snackbar({
            message: message,
            position: 'right-top',
            timeout: 4000,
            buttonText: '关闭',
            onButtonClick: () => true
        });
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.mdViewer = new MDViewer();
});